import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ui/api/db.dart';
import 'package:ui/api/http.dart';
import 'package:ui/view/setting/logic.dart';
import 'package:ui/view/tab_view/logic.dart';
import 'package:ui/view/update_prices/logic.dart';
import 'package:url_launcher/url_launcher.dart';

// getTemporaryDirectory() ：获取临时文件路径(IOS和安卓通用)
// getApplicationSupportDirectory() ：获取应用支持目录(IOS和安卓通用)
// getApplicationDocumentsDirectory() ：获取应用文件目录(IOS和安卓通用)，针对 Android 设备的 AppDate 目录，iOS 设备的 NSDocumentDirectory 目录
// getLibraryDirectory() ：获取应用持久存储目录路径(仅IOS可用)
// getExternalStorageDirectory() ： 获取存储卡目录(仅安卓可用)
// getExternalCacheDirectories() ：获取外部缓存目录(仅安卓可用)
// getDownloadsDirectory() ：获取下载目录(仅桌面可用)

Config config = Config();
Db db = Db();

class Config {
  double gFontSize = 28;
  // 配置的数据
  Map<String, dynamic> jsondata = {
    "uid": "",
    "topics": [],
    "host": "localhost"
  };
  // false HTTP  true MQTT
  bool switchvalue = false;
  // 设置页面
  final settingLogic = Get.put(SettingLogic());
  final tabViewLogic = Get.put(TabViewLogic());
  // 价格控制页面[复用]
  final updatePricesLogic = Get.put(UpdatePricesLogic());
  // 网络接口
  HTTP apihttp = HTTP();

  /// 利用SharedPreferences存储数据
  Future saveString(String storageKey, String str) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString(storageKey, str);
  }

  /// 获取存在SharedPreferences中的数据
  Future getString(String storageKey) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    Object? storageString = sharedPreferences.get(storageKey);
    return storageString;
  }

  // 文件存储：将数据保存到文件中  path_provider
  static Future<void> _save(String content, String filePath) async {
    final directory = await getExternalStorageDirectory();
    File file = File('${directory!.path}/$filePath');
    file.writeAsString(content);
  }

  // 文件读取
  static Future<String> _readFile(String filePath) async {
    try {
      final directory = await getExternalStorageDirectory();
      File file = File('${directory!.path}/$filePath');
      bool exist = await file.exists();
      if (!exist) return ''; // 判断文件是否存在

      return file.readAsString();
    } catch (e) {
      return '';
    }
  }

  savedata(map) async {
    await _save(map, './config.json');
  }

  Future getdate() async {
    String str = await _readFile('./config.json');
    if (str != '') {
      jsondata = jsonDecode(str);
      settingLogic.topicView.value = jsondata['topics'].cast<String>();
      settingLogic.uid.value = jsondata['uid'] ??
          Get.defaultDialog(
              title: "去获取巴发云密钥",
              titleStyle: const TextStyle(color: Colors.red, fontSize: 20),
              middleText: "确认跳转到网页",
              middleTextStyle: const TextStyle(color: Colors.red, fontSize: 14),
              contentPadding: const EdgeInsets.all(10),
              radius: 20,
              textCancel: "取消", //系统
              textConfirm: "确定",
              onCancel: () {
                debugPrint("点击了取消");
              },
              onConfirm: () async {
                Get.back();
                debugPrint("点击了确定");
                final Uri url =
                    Uri.parse('https://cloud.bemfa.com/tcp/index.html');
                if (!await launchUrl(url,
                    mode: LaunchMode.externalApplication)) {
                  throw Exception('Could not launch $url');
                }
              });
    } else {}
  }
}
